package cc.rengu.redp.system.service.impl;

import cc.rengu.redp.common.domain.RedpConstant;
import cc.rengu.redp.common.redis.RedisService;
import cc.rengu.redp.system.dao.CommonUserMapper;
import cc.rengu.redp.system.domain.User;
import cc.rengu.redp.system.service.CommonUserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class CommonUserServiceImpl extends ServiceImpl<CommonUserMapper, User> implements CommonUserService {

    @Autowired
    private RedisService redisService;
    @Autowired
    private ObjectMapper mapper;

    @Override
    public User findByName(String username) {
        return baseMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getUsername, username));
    }

    @Override
    public User getUserFromCache(String username) throws Exception {
        String userString = this.redisService.get(RedpConstant.USER_CACHE_PREFIX + username);
        if (StringUtils.isBlank(userString)) {
            throw new Exception();
        } else {
            return this.mapper.readValue(userString, User.class);
        }
    }
}
